package controller

import (
	"encoding/json"
	"net/http"
	"osiris/core/conversion"
	"osiris/core/state"
	"osiris/dto"
	"strconv"

	"github.com/gin-gonic/gin"
)

type PeerController struct{}

func (controller PeerController) GetHandler(context *gin.Context) {
	chainIDStr := context.Param("chainID")
	chainID, err := strconv.Atoi(chainIDStr)
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"chainID Atoi": err.Error(),
		})
		return
	}

	peerIDStr := context.Param("peerID")
	peerIDBytes, err := conversion.StrToPeerIDBytes(peerIDStr)
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"peerIDStr to bytes": err.Error(),
		})
		return
	}

	leaf, exist := state.GetPeerLeaf(peerIDBytes, chainID)

	peerStateDto:=dto.PeerStateDto{
		BaseDto: dto.BaseDto{
			Code: dto.CODE_PEER_NOT_EXIST,
		},
		PeerID: peerIDStr,
	}
	if exist {
		peerStateDto.Code = dto.CODE_PEER_EXIST
		peerStateDto.Asset = leaf.Asset
		peerStateDto.CoinSince = leaf.CoinSince
	}

	dtoBytes, err2 := json.Marshal(peerStateDto)
	if err2 != nil {
		context.JSON(http.StatusInternalServerError, gin.H{
			"PeerStateDto Serialization": err2.Error(),
		})
		return
	}
	context.JSON(http.StatusOK, string(dtoBytes))
}
